package com.zhuiyun.project.api.ancientPoetry.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zhuiyun.project.api.ancientPoetry.entity.AncientPoetry;
import com.zhuiyun.project.api.ancientPoetry.entity.Poetry;
import com.zhuiyun.project.api.ancientPoetry.mapper.AncientPoetryMapper;
import com.zhuiyun.project.api.ancientPoetry.model.AncientPoetryModel;
import com.zhuiyun.project.api.ancientPoetry.service.AncientPoetryService;
import com.zhuiyun.project.api.poetryAuthor.entity.PoetryAuthor;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.ObjectUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author shy
 * @Date 2023/12/6 19:04
 */
@Service
public class AncientPoetryServiceImpl implements AncientPoetryService {
    @Resource
    private AncientPoetryMapper ancientPoetryMapper;
    /**
     *
     * @Author shy
     * @Date 2023/12/7 11:47 TODO 分页查询诗词
      * @param ancientPoetryModel
     * @return CommonResult
     */
    @Override
    public CommonResult PageListPoetry(AncientPoetryModel ancientPoetryModel, PageRequest pageRequest) {
        //注意page 内容不能为空
        PageHelper.startPage(pageRequest);
        AncientPoetry poetryAuthor=BeanUtil.toBean(ancientPoetryModel,AncientPoetry.class);
        List<AncientPoetry> list=ancientPoetryMapper.selectPoetry(poetryAuthor);
        PageResult pageResult= MybatisPageHelper.getPageResult(list);
        if(ObjectUtils.isNotEmpty(pageResult)){
            return CommonResult.ok(pageResult);
        }else {
            return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
        }

    }
    /**
     *
     * @Author shy
     * @Date 2023/12/7 15:31 TODO 本地添加诗
     * @param path   本地文本存储的地址
     * 文本样式：Json类型
     *   最后一个文本必须要少一括号
     *   例：[{"author": "","paragraphs": "","title": ""},{},{]
     *
     */
    @Override
    public void URLInsert(String path) throws IOException {
        // path 诗词路径
        //读取诗词
        String content = FileUtils.readFileToString(new File(path), "UTF-8");
        //去除 空格换行
        String newContent=content.substring(1,content.length()-1).replaceAll("[\r\n]","").replaceAll(" ","");
        //截取成单个json
        String[] split = newContent.split("},");
        //转换成对象
        List<Poetry> collect = Arrays.stream(split).map(item -> JSONObject.parseObject(item+"}", Poetry.class)).collect(Collectors.toList());
        //截取100首
        List<Poetry> one = collect.subList(0, 101);
        one.forEach(item->{
            item.setContent(item.getParagraphs().toString().substring(1,item.getParagraphs().toString().length()-1));
            ancientPoetryMapper.insertReadPoetry(item);
        });
    }
    /**
     *
     * @Author shy
     * @Date 2023/12/7 15:44 TODO 根据id删除诗词
     * @param id
     * @return CommonResult
     */
    @Override
    public CommonResult DeletePoetry(Integer id) {
        if(id!=null&&id!=0){
            Example e=new Example(AncientPoetry.class);
            e.createCriteria().andEqualTo("poetryId",id);
            AncientPoetry a=new AncientPoetry();
            a.setDelFlag(1);
            a.setUpdateTime(new Date());
            int i=ancientPoetryMapper.updateByExampleSelective(a,e);
            if(i>0){
                return CommonResult.ok(EmErrorCode.DELETE_OK);
            }else {
                return CommonResult.error(EmErrorCode.DELETE_ERROR);
            }
        }else {
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }

    /**
     *
     * @Author shy TODO 添加诗词
     * @Date 2023/12/8 11:05
     * @param ancientPoetryModel
     * @return CommonResult
     */
    @Override
    public CommonResult insertPoetry(AncientPoetryModel ancientPoetryModel) throws CommonException {
        if(ValidatorUtil.ValidationObject(ancientPoetryModel)){
            AncientPoetry ancientPoetry= BeanUtil.toBean(ancientPoetryModel, AncientPoetry.class);
            ancientPoetry.setCreationTime(new Date());
            ancientPoetry.setDelFlag(0);
            int i=ancientPoetryMapper.insertSelective(ancientPoetry);
            if(i>0){
                return CommonResult.ok(EmErrorCode.SAVE_OK);
            }else {
                return CommonResult.error(EmErrorCode.SAVE_ERROR);
            }
        }else {
            throw new CommonException(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     *
     * @Author shy
     * @Date 2023/12/14 10:50 TODO 修改诗词
     * @param ancientPoetryModel
     * @return CommonResult
     */
    @Override
    public CommonResult updatePoetry(AncientPoetryModel ancientPoetryModel) throws CommonException {
        if(ValidatorUtil.ValidationObject(ancientPoetryModel)&&ancientPoetryModel.getPoetryId()!=null&&ancientPoetryModel.getPoetryId()!=0){
            AncientPoetry ancientPoetry=BeanUtil.toBean(ancientPoetryModel, AncientPoetry.class);
            ancientPoetry.setUpdateTime(new Date());
            Example e=new Example(AncientPoetry.class);
            e.createCriteria().andEqualTo("poetryId",ancientPoetry.getPoetryId());
            int i=ancientPoetryMapper.updateByExampleSelective(ancientPoetry,e);
            if(i>0){
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            }else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        }else {
            throw new CommonException(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

}